package com.spring.security.study.security_test.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.spring.security.study.security_test.api.SysUser;
import com.spring.security.study.security_test.api.SysUserDetails;
import com.spring.security.study.security_test.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName : SysUserLoginAuthentication
 * @Author : lby
 * @Date: 2021/1/25 15:28
 * @Description : 用户登录认证
 */
@Component
@AllArgsConstructor
public class SysUserLoginAuthentication implements AuthenticationProvider {

    private final SysUserService sysUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //1、获取表单输入的用户名
        String username = (String) authentication.getPrincipal();
        //2、获取表单输入的密码
        String password = (String) authentication.getCredentials();
        //3、查询用户是否存在
        QueryWrapper<SysUser> query = Wrappers.query();
        query.eq("user_name",username);
        SysUser sysUser = sysUserService.getOne(query);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        String basePassword="123456";
        if (!password.equals(basePassword)){
            throw new BadCredentialsException("密码不正确");
        }
        //查询用户角色
        SysUserDetails sysUserDetails = new SysUserDetails();
        sysUserDetails.setPassword(password);
        sysUserDetails.setUserName(username);
        sysUserDetails.setUserId(String.valueOf(sysUser.getId()));
        // 给用户赋予权限
        Set<GrantedAuthority> authorities = new HashSet<>();
            authorities.add(new SimpleGrantedAuthority("sys_user_view"));
        sysUserDetails.setAuthorities(authorities);
        //进行登录
        return new UsernamePasswordAuthenticationToken(sysUserDetails, password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
